package com.zh.springcloud.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zh.springcloud.common.Result;
import com.zh.springcloud.entity.Order;
import com.zh.springcloud.feign.AccountFeignService;
import com.zh.springcloud.feign.StorageFeignService;
import com.zh.springcloud.mapper.OrderMapper;
import com.zh.springcloud.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @ClassName OrderServiceImpl
 * @date: 2021.08.09 20:12
 * @Author: zhanghang
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private StorageFeignService storageFeignService;

	@Autowired
	private AccountFeignService accountFeignService;

	@Override
	@GlobalTransactional(name = "zh-create-order",rollbackFor = Exception.class)
	public Result<?> createOrder(Map<String, Object> map) {
		Long  productId = MapUtil.getLong(map,"productId");
		Integer count = MapUtil.getInt(map,"count");
		Long userId = MapUtil.getLong(map,"userId");
		BigDecimal money = new BigDecimal(MapUtil.getStr(map,"money"));
		// 新建订单
		log.info("------> 新建订单");
		Order order = new Order();
		Byte status_0 = 0;
		order.setStatus(status_0);
		order.setCount(count);
		order.setMoney(money);
		order.setUserId(userId);
		order.setProductId(productId);
		orderMapper.insert(order);

		log.info("------> 订单微服务开始调用库存，做扣减操作");
		storageFeignService.decrease(productId,count);
		log.info("------> 订单微服务开始调用库存，做扣减操作end");

		log.info("------> 订单微服务开始调用账户，做扣减余额操作");
		accountFeignService.decrease(userId,money);
		log.info("------> 订单微服务开始调用账户，做扣减余额操作");

		log.info("------> 修改订单状态");
		Order updateOrder = new Order();
		byte status = 1;
		updateOrder.setStatus(status);
		orderMapper.update(updateOrder,new QueryWrapper<Order>()
				.lambda()
				.eq(Order::getId,order.getId())
				.eq(Order::getStatus,0));

		log.info("------> 下订单结束");
		return Result.ok();
	}


}
